package cn.hznc.controller.order;

import cn.hznc.aspect.BusinessType;
import cn.hznc.aspect.Log;
import cn.hznc.controller.order.strategy.AbutmentDataConnectContext;
import cn.hznc.controller.order.strategy.AbutmentOrderDataContext;
import cn.hznc.controller.order.strategy.ZccAbutmentDataConnectStrategy;
import cn.hznc.controller.order.strategy.ZccAbutmentOrderDataStrategy;
import cn.hznc.controller.service.order.AbutmentService;
import cn.hznc.controller.service.process.ProcessManageService;
import cn.hznc.domain.entity.OrderEntity;
import cn.hznc.domain.request.order.*;
import cn.hznc.domain.response.PageResult;
import cn.hznc.domain.response.ResponseBody;
import cn.hznc.dto.OrderImport;
import cn.hznc.excel.OrderReadListener;
import cn.hznc.exception.SystemException;
import cn.hznc.exception.ToolManageException;
import cn.hznc.controller.service.order.OrderManageService;
import cn.hznc.permission.Permission;
import cn.hznc.utils.CommonUtil;
import cn.hznc.utils.FileUploadUtil;
import cn.hznc.vo.BomParamVo;
import cn.hznc.vo.CraftParamVo;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 工单管理接口
 *
 * @Author Administrator
 * @Date 2023/3/20 10:25
 */
@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/order")
@Slf4j
public class OrderManageController {
    @Resource
    private OrderManageService orderManageService;

    @Resource
    private ProcessManageService processManageService;

    @Resource
    private AbutmentService abutmentService;

    @Resource
    private ZccAbutmentOrderDataStrategy zccAbutmentOrderDataStrategy;

    @Resource
    private ZccAbutmentDataConnectStrategy zccAbutmentDataConnectStrategy;

    /**
     * 模糊查询工单号
     *
     * @return
     */
    @RequestMapping(value = "/queryOrderTaskId", method = RequestMethod.GET)
    public ResponseBody queryOrderTaskId(@RequestParam("taskId")String taskId) {
        return ResponseBody.success(orderManageService.queryOrderTaskId(taskId));
    }

    /**
     * 工单查询(分页)
     *
     * @param queryOrderReq queryOrderReq
     * @return
     */
    @RequestMapping(value = "/queryOrderList", method = RequestMethod.POST)
    @Permission(title = "工单查询(分页)" , permissions = {"orderManagement.read"})
    public ResponseBody<PageResult<OrderEntity>> queryOrderList(@RequestBody QueryOrderReqReload queryOrderReq) {
        return ResponseBody.success(orderManageService.queryOrderList(queryOrderReq));
    }

    @RequestMapping(value = "/updateInCraftBz", method = RequestMethod.POST)
    public ResponseBody updateInCraftBz(@RequestBody UpdateInCraftBzReq UpdateInCraftBzReq) {
        try {
            return ResponseBody.success(orderManageService.updateInCraftBz(UpdateInCraftBzReq));
        } catch (ToolManageException e) {
            return ResponseBody.error(e.getCode() , e.getMessage());
        }
    }

    /**
     * 工单编辑
     *
     * @param editOrderReq editOrderReq
     * @return
     */
    @RequestMapping(value = "/editOrder", method = RequestMethod.POST)
    @Log(title = "修改工单信息" , businessType = BusinessType.UPDATE)
    @Permission(title = "新增工单信息" , permissions = {"orderManagement.update"})
    public ResponseBody<Boolean> editOrder(@RequestBody EditOrderReq editOrderReq) {
        try {
            orderManageService.editorOrder(editOrderReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 工单新增
     *
     * @param createOrderReq createOrderReq
     * @return
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @Log(title = "新增工单信息" , businessType = BusinessType.INSERT)
    @Permission(title = "新增工单信息" , permissions = {"orderManagement.add"})
    public ResponseBody<Boolean> createOrder(@RequestBody CreateOrderReq createOrderReq) {
        try {
            orderManageService.createOrder(createOrderReq);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 工单删除
     *
     * @param ids ids
     * @return
     */
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
    @Log(title = "删除工单信息" , businessType = BusinessType.DELETE)
    @Permission(title = "删除工单信息" , permissions = {"orderManagement.delete"})
    public ResponseBody<Boolean> deleteOrder(@RequestBody List<Integer> ids) {
        try {
            orderManageService.deleteOrder(ids);
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 查询工单的物料的细节
     *
     * @param taskId orderId
     * @return
     */
    @RequestMapping(value = "/queryOrderBomDetail", method = RequestMethod.GET)
    public ResponseBody<List<BomParamVo>> queryOrderBomDetail(@RequestParam("taskId") String taskId) {
        try {
            return ResponseBody.success(orderManageService.queryOrderBomDetail(taskId));
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
    }

    /**
     * 查询工单的工艺的详情
     *
     * @param taskId orderId
     * @return
     */
    @RequestMapping(value = "/queryOrderCraftDetail", method = RequestMethod.GET)
    public ResponseBody<List<CraftParamVo>> queryOrderCraftDetail(@RequestParam("taskId") String taskId) {
        try {
            return ResponseBody.success(orderManageService.queryOrderCraftDetail(taskId));
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
    }

    /**
     * 编辑工单的工艺的详情
     *
     * @return
     */
    @RequestMapping(value = "/editOrderCraftList", method = RequestMethod.POST)
    @Log(title = "编辑工单工艺" , businessType = BusinessType.UPDATE)
    @Permission(title = "编辑工单工艺" , permissions = {"craftdetail.update"})
    public ResponseBody<Boolean> editOrderCraftList(@RequestBody EditOrderCraftReq editOrderCraftReq) {
        try {
            return ResponseBody.success(orderManageService.editOrderCraftList(editOrderCraftReq));
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
    }

    /**
     * 编辑工单的物料的详情
     *
     * @param editOrderBomReq editOrderBomReq
     * @return
     */
    @RequestMapping(value = "/editOrderBomList", method = RequestMethod.POST)
    @Permission(title = "编辑产品bom" , permissions = {"productiondetail.update"})
    public ResponseBody<Boolean> editOrderBomList(@RequestBody EditOrderBomReq editOrderBomReq) {
        try {
            return ResponseBody.success(orderManageService.editOrderBomList(editOrderBomReq));
        } catch (ToolManageException te) {
            return ResponseBody.error(te.getCode(), te.getMsg());
        }
    }

    /**
     * 工单导入
     *
     * @param file
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/importOrder", method = RequestMethod.POST)
    @Log(title = "工单excel导入" , businessType = BusinessType.OTHER)
    public ResponseBody<Boolean> importOrder(@RequestParam("file") MultipartFile file, HttpServletRequest httpServletRequest) {
        try {
            OrderReadListener orderReadListener = new OrderReadListener();
            FileUploadUtil.checkCommonFile(file);
            EasyExcel.read(file.getInputStream(), OrderImport.class, orderReadListener).headRowNumber(2).autoCloseStream(true).sheet().doRead();
            orderManageService.importOrder(orderReadListener.getImportData());
        } catch (IOException ex) {
            log.error("importOrder error========》", ex);
        } catch (SystemException systemException) {
            log.error("importOrder error========》msg：{}", systemException.getMsg());
            return ResponseBody.error(systemException.getCode(), systemException.getMsg());
        }
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 导出工单模版excel
     *
     * @return
     */
    @RequestMapping(value = "/exportOrderTemplate", method = RequestMethod.POST)
    public ResponseBody<Boolean> exportOrderTemplate(HttpServletResponse response) {
        orderManageService.exportOrderTemplate(response);
        return ResponseBody.success(Boolean.TRUE);
    }

    /**
     * 导出工件详细参数
     * @param response
     */
    @RequestMapping(value = "/exportOrder", method = RequestMethod.GET)
    public void exportOrder(HttpServletResponse response) {
        try {
            orderManageService.exportOrder(response);
        } catch (IOException e) {
            log.error("exportToolForkInfo error========》msg：{}" + e.getMessage());
        }
    }

    /**
     * 导出工单模版
     *
     * @return
     */
    @RequestMapping(value = "/exportOrderDetail", method = RequestMethod.GET)
    public void exportOrderDetail(HttpServletResponse response, @RequestParam("orderId") Integer orderId) {
        orderManageService.exportOrderDetail(response, orderId);
    }




    @RequestMapping(value = "/checkProgramKanBan", method = RequestMethod.GET)
    public ResponseBody<Map<String , Object>> checkProgramKanBan(@RequestParam("taskId") String taskId,
                                                                       @RequestParam("code") String code,
                                                                       @RequestParam("equipmentId")Integer equipmentId) {
        return ResponseBody.success(orderManageService.checkProgramKanBan(taskId, code , equipmentId));
    }

    /**
     * 工单任务分配子表
     * @param taskId
     * @return
     */
    @RequestMapping(value = "/selectCraftTaskChild", method = RequestMethod.GET)
    public ResponseBody selectCraftTaskChild(@RequestParam("taskId") String taskId , @RequestParam("seq") Integer seq) {
        return ResponseBody.success(orderManageService.selectCraftTaskChild(taskId, seq));
    }

    /**
     * 工单任务分配修改
     * @return
     */
    @RequestMapping(value = "/editCraftTask", method = RequestMethod.POST)
    @Log(title = "分配任务修改" , businessType = BusinessType.UPDATE)
    public ResponseBody editCraftTask(@RequestBody EditCraftTaskReq editCraftTaskReq) {
        try {
            return ResponseBody.success(processManageService.editCraftTask(editCraftTaskReq));
        } catch (ToolManageException e) {
            System.out.println("e.getMsg() = " + e.getMsg());
            return ResponseBody.error(e.getCode(),e.getMessage());
        }
    }

    @RequestMapping(value = "/CompleteTheTask", method = RequestMethod.POST)
    public ResponseBody CompleteTheTask(@RequestParam("taskId") String taskId , @RequestParam("seq") Integer seq){
        orderManageService.CompleteTheTask(taskId,seq);
        return ResponseBody.success();
    }

    @RequestMapping(value = "/lackOrderProgram", method = RequestMethod.POST)
    public ResponseBody lackOrderProgram(@RequestBody QueryOrderReq queryOrderReq){
        return ResponseBody.success(orderManageService.lackOrderProgram(queryOrderReq));
    }

//    @RequestMapping(value = "/abutmentOrder", method = RequestMethod.POST)
//    public ResponseBody abutmentOrder(@RequestBody AbutmentOrderReq abutmentOrderReq){
//        orderManageService.abutmentOrder(abutmentOrderReq);
//        return ResponseBody.success();
//    }

    @RequestMapping(value = "/abutmentData", method = RequestMethod.POST)
    @Log(title = "根据时间范围拉取工单信息" , businessType = BusinessType.INSERT)
    public ResponseBody abutmentData(@RequestBody AbutmentOrderReq abutmentOrderReq){
        //abutmentService.abutmentData(abutmentOrderReq);
        AbutmentOrderDataContext abutmentOrderDataContext = new AbutmentOrderDataContext(zccAbutmentOrderDataStrategy);
        return ResponseBody.success(abutmentOrderDataContext.abutmentData(abutmentOrderReq));
    }

    @RequestMapping(value = "/abutmentDataReload", method = RequestMethod.GET)
    //@Log(title = "指定工单号拉取工单信息" , businessType = BusinessType.INSERT)
    public ResponseBody abutmentDataReload(@RequestParam("taskIds") List<String> taskIds){
        //abutmentService.abutmentDataReload(taskIds);
        AbutmentOrderDataContext abutmentOrderDataContext = new AbutmentOrderDataContext(zccAbutmentOrderDataStrategy);
        return ResponseBody.success(abutmentOrderDataContext.abutmentData(taskIds));
    }

    @RequestMapping(value = "/deleteData", method = RequestMethod.GET)
    //@Log(title = "指定工单号拉取工单信息" , businessType = BusinessType.INSERT)
    public ResponseBody deleteData(@RequestParam("taskIds") List<String> taskIds){
        abutmentService.deleteData(taskIds);
        return ResponseBody.success();
    }

    @RequestMapping(value = "/abutmentDataTest", method = RequestMethod.GET)
    public ResponseBody abutmentDataTest() throws ParseException {
        AbutmentOrderReq abutmentOrderReq = new AbutmentOrderReq();
        Map<String, String> dateMap = CommonUtil.minusTime24h();
        abutmentOrderReq.setStartTime(CommonUtil.parseDateReload(dateMap.get("Data2")));
        abutmentOrderReq.setEndTime(CommonUtil.parseDateReload(dateMap.get("Data1")));
        abutmentOrderReq.setMaterialNos(Arrays.asList("434" , "435" , "437"));
        abutmentService.abutmentData(abutmentOrderReq);
        return ResponseBody.success();
    }

    @RequestMapping(value = "/abutmentDataConnect", method = RequestMethod.GET)
    public ResponseBody abutmentDataConnect(){
        AbutmentDataConnectContext abutmentDataConnectContext = new AbutmentDataConnectContext(zccAbutmentDataConnectStrategy);
        return ResponseBody.success(abutmentDataConnectContext.abutmentDataConnect());
        //return ResponseBody.success(abutmentService.abutmentDataConnect());
    }

    @RequestMapping(value = "/allotedLackOrderProgram", method = RequestMethod.POST)
    public ResponseBody allotedLackOrderProgram(@RequestBody QryOrderReq qryOrderReq){
        return ResponseBody.success(orderManageService.allotedLackOrderProgram(qryOrderReq));
    }

    @RequestMapping(value = "/orderCraft", method = RequestMethod.POST)
    public ResponseBody orderCraft(@RequestBody QueryOrderReloadReq queryOrderReloadReq){
        try {
            return ResponseBody.success(orderManageService.orderCraft(queryOrderReloadReq));
        } catch (ToolManageException e) {
            return ResponseBody.error(e.getCode() , e.getMessage());
        }
    }

    @RequestMapping(value = "/queryOrderListReload", method = RequestMethod.POST)
    public ResponseBody queryOrderListReload(@RequestBody QueryOrderReq queryOrderReq){
        return ResponseBody.success(orderManageService.queryOrderListReload1(queryOrderReq));
    }

    @RequestMapping(value = "/getAllTaskIds", method = RequestMethod.GET)
    public ResponseBody getAllTaskIds(){
        return ResponseBody.success(orderManageService.getAllTaskIds());
    }

//    @RequestMapping(value = "/abutmentOrderStatus", method = RequestMethod.POST)
//    public ResponseBody abutmentOrderStatus(@RequestBody List<String> taskIds){
//         return ResponseBody.success(orderManageService.abutmentOrderStatus(taskIds));
//    }
//    @RequestMapping(value = "/abutmentOrderStatus", method = RequestMethod.GET)
//    @Log(title = "同步工单以及工序状态" , businessType = BusinessType.UPDATE)
//    public ResponseBody abutmentOrderStatus(@RequestBody List<String> taskIds){
//        //List<String> taskIds = Arrays.asList("40103504    ");
//        return ResponseBody.success(orderManageService.abutmentOrderStatus(taskIds));
//    }

    @RequestMapping(value = "/abutmentOrderStatus", method = RequestMethod.POST)
    @Log(title = "同步工单以及工序状态" , businessType = BusinessType.UPDATE)
    public ResponseBody abutmentOrderStatus(@RequestBody List<String> taskIds){
        //List<String> taskIds = Arrays.asList("40103504    ");
        return ResponseBody.success(orderManageService.abutmentOrderStatus(taskIds));
    }

    @RequestMapping(value = "/setOrderCraftTypeFlag", method = RequestMethod.GET)
    //@Log(title = "同步工单以及工序状态" , businessType = BusinessType.UPDATE)
    public ResponseBody setOrderCraftTypeFlag(){
        return ResponseBody.success(orderManageService.setOrderCraftTypeFlag());
    }


}